// 物料组
import { Input, Button, Space, Table, Modal, Form, Select, Row, Col, message, Popconfirm, Switch, DatePicker, DatePickerProps, Pagination } from 'antd';
import React from 'react';
import { useState, useEffect } from 'react'
import type { ColumnsType } from 'antd/lib/table';
import { SearchOutlined, SyncOutlined, DownloadOutlined, CloudDownloadOutlined } from '@ant-design/icons';
import itemgroup from './itemgroup.module.scss'
import axios from '../../../utils/axios'
import moment from 'moment';
import 'moment/locale/zh-cn';
const BasicManagement = () => {
  const [datay, setDatay] = useState<DataType[] | undefined>()
  // 获取数据
  const getdata = () => {
    axios({
      url: '/material/selectMaterial',
    }).then(res => {
      console.log(res.data.data.listMaterial);
      setDatay(res.data.data.listMaterial)
    }).catch(error => console.log(error)
    )
  }
  useEffect(() => {
    getdata()
  }, [])
  // 搜索值
  const [searchid, setSearchid] = useState<string>()
  const [searchgroup, setSearchgroup] = useState<string>()
  const onsearchid = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setSearchid(e.target.value)
  };
  const onsearchgroup = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setSearchgroup(e.target.value)
  };
  const searchval = () => {
    console.log(searchid, searchgroup);
    axios({
      url: '/material/selectMaterial',
      params: { materialNumber: searchid, materialName: searchgroup }
    }).then(res => {
      setDatay(res.data.data.listMaterial)
    }).catch(error => console.log(error)
    )
  }
  // 重置
  const resolve = () => {
    setSearchid('')
    setSearchgroup('')
    axios({
      url: '/material/selectMaterial',
    }).then(res => {
      setDatay(res.data.data.listMaterial)
    }).catch(error => console.log(error)
    )
  }
  // 设置修改表单的数据
  const [editForm] = Form.useForm();
  const [addForm] = Form.useForm();
  // tab表格
  interface DataType {
    materialNumber: number;//物料组代号
    materialId: number;//序列号
    materialName: string;//物料组
    sampleProcedureName: string;//抽样方案
    materialTime: string;//维护时间
    userName: string;//操作人
  }
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'materialId',

    },
    {
      title: '物料组代号',
      dataIndex: 'materialNumber',

    },
    {
      title: '物料组',
      dataIndex: 'materialName',

    },
    {
      title: '抽样方案',

      dataIndex: 'sampleProcedureName',
    }
    ,
    {
      title: '维护时间',

      dataIndex: 'materialTime',
    },

    {
      title: '操作人',

      dataIndex: 'userName',
    },
    {
      title: '操作',

      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => {
            setEditIsModalVisible(true);
            editForm.setFieldsValue(record)
            setLasttime(record.materialTime)
          }}>编辑</a>
          <Popconfirm
            title="确认删除吗"
            onConfirm={() => { confirm(record.materialId) }}
            okText="确认"
            cancelText="取消"
          >
            <a href="#">删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  //弹出框的隐藏关闭
  // 添加
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  // 修改
  const [isEditModalVisible, setEditIsModalVisible] = useState(false);
  // 添加模态框
  const addmodule = () => {
    addForm.resetFields()
    setIsAddModalVisible(true)
  }
  // 添加完成
  const addhandleOk = () => {
    setIsAddModalVisible(false);
    console.log(addForm.getFieldsValue());
    let materialNumber=Number(addForm.getFieldsValue().materialNumber)
    let sampleProcedureId=Number(addForm.getFieldsValue().sampleProcedureId)
    let materialName=String(addForm.getFieldsValue().materialName)
    let userId=Number(addForm.getFieldsValue().userId)
    console.log(moment().format('YYYY-MM-DD HH:mm:ss'));
    axios(
      {url:'/material/addMaterial',
      method:'post',
      data:{materialNumber,sampleProcedureId,materialName,userId,materialTime:moment()}
    }
      ).then(res=>{
        console.log(res);
        if (res.status===200) {
          getdata()
        }
      }).catch(error=>console.log(error)
      )
  };
  // 取消添加
  const addhandleCancel = () => {
    setIsAddModalVisible(false);
  };
  // 编辑模态框
  const handleOk = () => {
    setEditIsModalVisible(false);
    console.log(editForm.getFieldsValue(),lasttime);
    axios({
      url:'/material/updateMaterial',
      method:'post',
      data:{...editForm.getFieldsValue(),materialTime:lasttime}
    }).then(res=>{
      console.log(res);
      if (res.status===200) {
        getdata()
      }
    }).catch(error=>console.log(error)
    )

  };
  const handleCancel = () => {
    setEditIsModalVisible(false);
  };
  // 删除确认按钮
  const confirm = (id: number) => {
    axios({
      url: `/material/deleteMaterial`,
      params: { materialId: id }
    }).then(res => {
      if (res.data.code == 200) {
        message.success('删除成功');
        getdata()
      }
    }).catch(error => console.log(error)
    )
  };
  // 维护时间
  const [lasttime, setLasttime] = useState<string>()
  // 上次次型式时间
  const timeChange: DatePickerProps['onChange'] = (date, dateString) => {
    console.log(date, dateString);
    setLasttime(dateString)
  };
  // 表格分页功能
  // 页面跳转
  const tarpage = (page: number, pageSize: number) => {
    console.log(page, pageSize);
    console.log(333);
    // axios({
    //   url: `/material/selectMaterial`,
    //   params:{limit:pageSize,page:page}
    // }).then(res => {
    //   console.log(res);
    //   if (res.data.code==200) {
    //     message.success('查询成功');
    //     console.log(res);
    //     setDatay(res.data.data.listMaterial)
    //   // getdata()
    //   }
    // }).catch(error => console.log(error)
    // )
  }
  return <div className={itemgroup.box}>
    {/* 搜索按钮 */}
    <div>
      <label htmlFor="">物料组代号:</label>
      <Input className={itemgroup.searchone} style={{ width: 200 }} placeholder="物料组编号" value={searchid} allowClear onChange={onsearchid} />
      <label htmlFor="">物料组:</label>
      <Input className={itemgroup.searchone} style={{ width: 200 }} placeholder="物料组" allowClear value={searchgroup} onChange={onsearchgroup} />
      <Button style={{ color: '#1890FF', border: '1px solid #2696FF', marginRight: 20 }} onClick={() => { searchval() }} icon={<SearchOutlined />}>查询</Button>
      <Button style={{ color: '#ffc069', border: '1px solid #ffc069' }} onClick={() => { resolve() }} icon={<SyncOutlined style={{ color: '#ffc069' }} />}>重置</Button>
    </div>
    {/* 新增等功能 */}
    <div className={itemgroup.tewbox}>
      <Button onClick={() => { addmodule() }} style={{ marginRight: 10 }} type="primary" size={'small'}>
        +新增
      </Button>
      <Button icon={<DownloadOutlined />} style={{ marginRight: 10 }} type="primary" size={'small'}>
        导入
      </Button>
      <Button icon={<CloudDownloadOutlined />} type="primary" size={'small'}>
        模板下载
      </Button>
    </div>
    {/* 表格 */}
    {/* pagination={{ hideOnSinglePage: true, showQuickJumper: true, defaultPageSize: 2, showTotal: (total, range) => `共 ${total} 条`, position: ["bottomCenter"] }} */}
    {/* onChange={handleTableChange} */}
    <div>
      <Table pagination={{ hideOnSinglePage: true, showQuickJumper: true, defaultPageSize: 2, showTotal: (total, range) => `共 ${total} 条`, position: ["bottomCenter"] }}
        rowKey={(record) => { return record.materialId }} columns={columns} dataSource={datay} />
      {/* <Pagination
        total={datay?.length}
        showSizeChanger
        showQuickJumper
        showTotal={total => `共 ${total} 条`}
        pageSizeOptions={[2, 5, 8, 10]}
        defaultPageSize={2}
        style={{height: '32px', lineHeight: '32px', textAlign: 'center'}}
        onChange={(page, pageSize) => {
          // 页码跳转
          tarpage(page,pageSize)
        }}

      /> */}
    </div>
    {/* 模态框 */}
    <div>
      <Modal title="物料组修改" visible={isEditModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <Form
          form={editForm}
          name="basic"
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 16,
          }}
          autoComplete="off"
        >
          <Form.Item
            label="序列号"
            name={"materialId"}
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input disabled />
          </Form.Item>

          <Form.Item
            label="物料组代号"
            name={"materialNumber"}
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="物料组"
            name={"materialName"}
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="抽样方案"
            name={"sampleProcedureName"}
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="维护时间"
          >
            <DatePicker onChange={timeChange} defaultValue={moment(lasttime, 'YYYY-MM-DD')} />

          </Form.Item>
          <Form.Item
            label="操作人"
            name={"userName"}
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
    {/* 新增 */}
    <div>
      <Modal title="物料组新增" visible={isAddModalVisible} onOk={addhandleOk} onCancel={addhandleCancel}>
        <Form
          form={addForm}
          name="basic"
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 16,
          }}
          autoComplete="off"
        >
          <Form.Item
            label="材料组编号"
            name={"materialNumber"}
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="材料组名称"
            name={"materialName"}
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="抽样方案id"
            name={"sampleProcedureId"}
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="维护人id"
            name={"userId"}
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  </div>
}
export default BasicManagement
